<template>
  <div class="home">
    <div class="title">内容</div>

    <VueUeditorWrap
      ref="iframeRef"
      v-model="msg"
      :config="editorConfig"
      editor-id="editor-demo-01"
      @dblclick="dblclickHandle"
      @ready="ready"
    ></VueUeditorWrap>
    <div>双击编辑器内容区或图片打开</div>
    <div class="content" ref="contentRef"></div>
    <DrawDialog ref="drawDialogRef" @closeHandle="closeHandle1"></DrawDialog>
  </div>
</template>

<script setup>
import { ref } from 'vue'
import DrawDialog from './drawDialog.vue'

const drawDialogRef = ref()

const contentRef = ref()
const currentDom = ref()
const iframeRef = ref()
const msg = ref()
const editorIn = ref()
// '<img src="dat>',
// https://p26.toutiaoimg.com/origin/tos-cn-i-qvj2lq49k0/22f10850c5234b5285350743cfa16357
const editorConfig = ref({
  // 编辑器不自动被内容撑高
  autoHeightEnabled: false,
  // 初始容器高度
  initialFrameHeight: 240,
  // 初始容器宽度
  initialFrameWidth: '100%',
  imagePopup: true,
  // 上传文件接口（这个地址是我为了方便各位体验文件上传功能搭建的临时接口，请勿在生产环境使用！！！）
  serverUrl: 'http://localhost:3000/upload',
  // UEditor 资源文件的存放路径，如果你使用的是 vue-cli 生成的项目，通常不需要设置该选项，vue-ueditor-wrap 会自动处理常见的情况，如果需要特殊配置，参考下方的常见问题2
  UEDITOR_HOME_URL: '/static/UEditor/',
  configUrl: import.meta.env.VITE_API_URL + '/info/uEditor/config',
  // 上传服务路径
})
const ready = (editorInstance) => {
  console.log('drawio实体', editorInstance)
  editorIn.value = editorInstance

  editorInstance.body.ondblclick = dblclickHandle
}

const dblclickHandle = (e) => {
  console.log('e双击', e)

  const img = editorIn.value.selection.getRange().getClosedNode()
  // currentDom.value = e.srcElement || e.target
  currentDom.value = img ?? (e.srcElement || e.target)
  drawDialogRef.value.openDialog(currentDom.value.getAttribute('src'))
}

const closeHandle1 = (data) => {
  if (data && data != '') {
    if (currentDom.value.tagName == 'IMG') {
      currentDom.value.setAttribute('src', data)
    } else {
      const imgEl = document.createElement('img')
      imgEl.src = data
      // console.log(data)
      // msg.value = imgEl.outerHTML
      // return
      editorIn.value.execCommand(
        'inserthtml',
        '<img class="nomaxdraw" src="' +
          data +
          '" data-json=\'' +
          JSON.stringify({ data }) +
          "' />",
      )
      contentRef.value.appendChild(imgEl)
    }
  }
  currentDom.value = null
}
</script>

<style scoped>
.home {
  height: 100%;
  display: flex;
  flex-direction: column;
}
.content {
  flex: 1;
}
</style>
